<script setup>
import {ref} from "vue";
import local from "@/axios/local";
import {ElMessage} from "element-plus";

const emits = defineEmits(['success'])
const props = defineProps(['file_path'])
const dataList = ref([])
const selection = ref([])
const treeNode = ref(null)
const defaultProps = {
  label: 'name',
  children: 'children'

}
const visible = ref(false)

function handleNodeClick(e, b, c, d) {
  console.log(e, b, c, d)
  treeNode.value = e
}

async function show(data) {
  visible.value = true
  selection.value = data
  treeNode.value = null
  await getTree()
}

function setChildren(data, ids) {
  data.forEach(el => {
    el.children = el.children.filter(item => !ids.includes(item.id))
    if (el.children.length > 0) {
      setChildren(el.children, ids)
    }
  })
  return data
}

async function getTree() {
  let {data} = await local.get('/cloud/getCloudAllFolder')
  let ids = selection.value.map(el => el.id)
  console.log(ids)
  data = data.filter(el => !ids.includes(el.id))
  dataList.value = setChildren(data, ids)
}


async function toMove() {
  let ids = selection.value.map(el => el.id)
  if (treeNode.value) {
    if (ids.includes(treeNode.value.id)) return ElMessage.warning('不能选择当前文件夹')
  }
  let arr = []


  selection.value.forEach(el => {
    let targetBucket = ''
    if (el.is_folder === 1) {
      targetBucket = treeNode.value ? treeNode.value.path + el.name +'/' : el.name +'/'
    }else{
      targetBucket = treeNode.value ? treeNode.value.path + el.name  : el.name
    }
    arr.push({
      name: el.name,
      srcBucket: el.path,
      targetBucket
    })
  })
  await local.post('/cloud/moveCloudFiles', {
    idList: ids,
    parent_id: treeNode.value ? treeNode.value.id : null,
    tasks: arr
  })
  visible.value = false
  ElMessage.success('操作成功')
  emits('success')
}


defineExpose({
  show
})
</script>

<template>
  <div class="move">
    <el-dialog draggable title="移动" v-model="visible">
      <el-tree
          style="max-width: 600px"
          :highlight-current="true"
          :default-expand-all="true"
          :data="dataList"
          node-key="id"
          :props="defaultProps"
          @node-click="handleNodeClick"
      />
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="toMove">移动</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>